package lwk.juc.lock;

import java.util.concurrent.TimeUnit;

/**
 * @author:lwk
 * @create: 2022-08-26 21:43
 * @Description: 死锁排查
 *
 * jps -l 查看进行的java线程
 *
 * jstack 线程号 查看线程的堆栈信息
 *
 */
public class DeadLock {

    public static void main(String[] args) {
        String l1 = "lockA";
        String l2 = "lockB";

        new Thread(new MyThread(l1,l2)).start();
        new Thread(new MyThread(l2,l1)).start();

    }

}


class MyThread implements Runnable {

    private final String lockA;
    private final String lockB;

    public MyThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {

        synchronized (lockA) {

            System.out.println(Thread.currentThread().getName() + "拿到了" + lockA + "想去获取" + lockB);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName() + "拿到了" + lockB + "想去获取" + lockA);
            }

        }


    }
}
